/**
 * Created by zlj on 2017/1/14.
 */
require("jquery");
require('layout/util');
var $form = require('js-path/formValide.js');
var $alert = require('libs/alert');

$(function () {
    judgeUpdateOrAdd();
    formInit();
    $("#client_back").on("click",function () {
        window.history.back();
    });
    $("#submit_form").on("click",function () {
        $("#client_form").submit();
    });
});

function formInit() {
    $form({selector:"#client_form"},{clientId:{required:true},resourceIds:{required:true},clientSecret:{required:true},
        webServerRedirectUri:{required:true}},{clientId:{required:'终端代码不能为空'},
        resourceIds:{required:'资源ID不能为空'},clientSecret:{required:'终端密钥不能为空'}, webServerRedirectUri:{required:'跳转地址不能为空'}},
        function () { return  $("#client_form").serializeObject() },function (result) {
                        if(result.code == 200){
                            window.location.href = 'client-manage';
                        }else {
                            $alert(result.message);
                        }
        }
    );
}

function judgeUpdateOrAdd() {
    var url = window.location.href;
    if(url.indexOf("id=")>0){
        $("#client_form").attr("action","api/v1/p/mms/client/update");
        $('span.name:first').html('修改client资源');
        var id = $.getUrlParam('id');
        load(id);
    }
}

function load(id) {
    $.ajax({
        url:'api/v1/p/mms/client/load',
        type:'post',
        data:{id:id},
        dataType:'json',
        success:function (result) {
            if(result.code == 200){
                $("#client_form").setForm(result.data);
            }else{
                $alert(result.message);
            }
        },
        error:function () {
            console.error('接口: api/v1/p/mms/client/load 失败')
        }
    })
}